import { BASE_URL } from '@/api/request'

function getToken() {
    return uni.getStorageSync('token') || ''
}

export default function fileSys() {
    return new Promise((resolve, reject) => {
        const main = plus.android.runtimeMainActivity()
        const Intent = plus.android.importClass('android.content.Intent')
        const Activity = plus.android.importClass('android.app.Activity')
        const Uri = plus.android.importClass('android.net.Uri')

        // 使用 SAF 选择文件，兼容安卓6~14，且无需权限
        const intent = new Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.setType('*/*')
        intent.addCategory(Intent.CATEGORY_OPENABLE)

        main.startActivityForResult(intent, 200)

        main.onActivityResult = (requestCode, resultCode, data) => {
            if (requestCode === 200 && resultCode === Activity.RESULT_OK && data && data.getData()) {
                const uri = data.getData()
                const filePath = uri.toString() // content://xxx

                uni.showLoading({ title: '上传中...', mask: true })

                uni.uploadFile({
                    url: BASE_URL + '/fileApi/File/UploadFiles',
                    filePath,
                    name: 'file',
                    header: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': getToken(),
                    },
                    formData: {
                        type: 'file'
                    },
                    success: (res) => {
                        uni.hideLoading()
                        try {
                            const parsed = JSON.parse(res.data)
                            if (parsed.code || parsed.isSuccess) {
                                resolve(parsed.result)
                            } else {
                                reject(parsed)
                            }
                        } catch (e) {
                            reject('解析失败：' + e.message)
                        }
                    },
                    fail: (err) => {
                        uni.hideLoading()
                        reject('上传失败：' + (err.errMsg || JSON.stringify(err)))
                    }
                })
            } else {
                reject('未选择文件或操作取消')
            }
        }
    })
}
